

#include <vfs.h>
#include <fs/fileinfo.h>
#include <asset/reader/assetreaderimage.h>
#include <gfx/image.h>
#include <IL/il.h>

ceAssetReaderImage::ceAssetReaderImage()
{
	CE_OBJECT_CONSTR
}




bool ceAssetReaderImage::CanRead(ceEngine *engine, ceAssetTypeID type, const ceAssetLocator &locator)
{
	if (type != ceImage::AssetTypeID)
		{
			return false;
		}


	ceFileInfo info (locator.GetLocation());

	std::string ext = info.GetExtension();

	return  ext == "jpeg"
			||  ext == "jpg"
			||  ext == "png"
			||  ext == "bmp"
			||  ext == "tga";
}

ceRef<ceAsset> ceAssetReaderImage::Read(ceEngine *engine, ceAssetTypeID type, const ceAssetLocator &locator)
{
	iFile *file = ceVFS::Get()->Open(locator.GetLocation());
	if (!file)
		{
      return 0;
		}

	ILuint name = ilGenImage();
	ilBindImage(name);

	file->Seek(SP_End, 0);
	long size = file->Tell();
	file->Seek(SP_Set, 0);

	char* data = new char[size+1];
	file->Read(data, size);
	file->Close();
	file->Release();
	data[size] = '\0';

	if (ilLoadL(IL_TYPE_UNKNOWN, data, size) == IL_FALSE)
		{
			printf ("Image Could not be loaded from data lump\n");
			delete [] data;
			return 0;
		}
	delete [] data;

	ceImage::Description desc;
	desc.width = ilGetInteger(IL_IMAGE_WIDTH);
	desc.height = ilGetInteger(IL_IMAGE_HEIGHT);
	ILenum format = ilGetInteger(IL_IMAGE_FORMAT);
	unsigned bpp = ilGetInteger(IL_IMAGE_BPP);

	switch (format)
		{
		case IL_RGB:
			desc.format   = PF_R8G8B8;
			break;
		case IL_RGBA:
			desc.format   = PF_R8G8B8A8;
			break;
		case IL_LUMINANCE:
			ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
			desc.format = PF_R8G8B8A8;
			break;
		default:
			if (bpp == 3)
				{
					ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
					desc.format = PF_R8G8B8;
				}
			else if (bpp == 4)
				{
					ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
					desc.format = PF_R8G8B8A8;
				}
			else
				{
					ilDeleteImage(name);
					return 0;
				}
		}

	ceImage* image = new ceImage();
  image->SetLocator(locator);
	if (!image->Initialize(desc, ilGetData()))
		{
			delete image;
			ilDeleteImage(name);
			return 0;
		}

	ilDeleteImage(name);
	return image;

}
